//分站管理的控制器
package org.csu.wuliu.controller;

import org.csu.wuliu.domain.*;
import org.csu.wuliu.persistence.ItemMapper;
import org.csu.wuliu.persistence.LineItemMapper;
import org.csu.wuliu.service.OrderService;
import org.csu.wuliu.service.SubstationService;
import org.csu.wuliu.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.sql.Ref;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/submanage")
public class SubmanageController {

    @Autowired
    private SubstationService substationService;

    @Autowired
    private LineItemMapper lineItemMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private TaskService taskService;

    //管理员：依据日期获得任务单列表（所有）
    //由前端来处理按什么排序！！
    @GetMapping("/admin/task")
    public List<Task> getTaskList(@RequestParam("substationId") String substationId){
        List<Task> taskList = substationService.getTaskListBySubstation(substationId);
        return taskList;
    }

    //通用：依据任务单号查询具体任务单
    @GetMapping("/task/{taskId}")
    public Task getTask(@PathVariable("taskId") String taskId){
        Task task = substationService.getTaskByTaskId(taskId);
        return task;
    }

    //依据配送员ID获得任务单列表（所有）
    @GetMapping("/distributor/{distributorId}/task")
    public List<Task> getMyTask(@PathVariable("distributorId") String distributorId){
        List<Task> taskList = substationService.getTaskListByDistributorId(distributorId);
        return taskList;
    }

    //任务单状态修改：配送员收到分配的任务后，选择是否接受
    //配送员ID是分配时就确定的
    @PutMapping("/distributor/{distributorId}/task")
    public Task setTaskStatus(@RequestBody Task task){
        task.setStatus(1);
        Order order = orderService.getOrder(task.getOrderId());
        order.setStatus(5);
        orderService.updateOrder(order);
        //handoutTask("TS202007120001");
        return substationService.updateTask(task);
    }

    //任务单分配：总部分配后调用本方法；本方法分配后发送短信或邮件给配送员；对所有分站适用
    //暂时未实现，需要彭波调用
    public void handoutTask(String taskId){
        Task task = substationService.getTaskByTaskId(taskId);

        //获取该任务单的分站
        String substationId = task.getSubstationId();
        //查看该分站各个配送员的任务量，平均分配
        //获取当前任务数最少的配送员的员工号
        String distributorId = getMinDistributor(substationId);

        task.setDistributorId(distributorId);
        substationService.updateTask(task);
        //任务单4种状态：0未分配/已分配未确认，1已分配待发货，2已分配拒绝任务，3已完成
    }

    //获取当前任务数量最少的配送员的员工号
    public String getMinDistributor(String substationId){
        //获得该分站所有配送员
        List<Distributor> distributorList = substationService.getDistributorListBySubstationId(substationId);
        //对每一个配送员，查找正在配送的任务单数量（status = 1）
        int min = 100;                   //目前最少的任务数
        String distributorId = "-1";     //目前最少的配送员工号；初始化为-1
        //对配送员遍历
        for(int i=0;i<distributorList.size();i++){
            Distributor distributor = distributorList.get(i);
            int number = 0;     //该配送员的初始任务数
            List<Task> taskList = substationService.getTaskListByDistributorId(distributor.getDistributorId());
            //对该配送员的所有任务遍历
            for(int j=0;j<taskList.size();j++){
                Task task = taskList.get(j);
                //如果是正在配送或等待确认的，任务数就加一
                if(task.getStatus()==1 || task.getStatus()==0){
                    number++;
                }
            }
            //与当前最少的比较，若更少则置换；注意剔除-1这个占位的
            if(number<min && !distributor.getDistributorId().equals("-1")){
                min = number;
                distributorId = distributor.getDistributorId();
            }
        }

        System.out.println("当前最少任务的配送员工号："+distributorId);
        return distributorId;
    }

    //打印签收单：在配送接受任务时调用，前端判断是否为接受状态。
    //前端：   if(task.getStatus() == 1) printSign(taskId);
    // 点击“打印签收单”后打印在屏幕上
    @PostMapping("/sign/{taskId}")
    public String printSign(@PathVariable("taskId") String taskId){
        //先看是否已经生成过签收单
        Sign sign = substationService.getSignByTaskId(taskId);
        //若还没生成过
        if(sign==null){
            //自动生成签收单号
            sign = new Sign();
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmm");
            String dateStr = formatter.format(date);
            System.out.println(dateStr);
            //从数据库获取已有的最后一个签收单号？？
            String signId = "QS"+ dateStr;
            //为sign赋值：任务单号（签收人手动输入或取消）！！
            sign.setSignId(signId);
            sign.setTaskId(taskId);
            sign.setName("");
            sign.setImage("");
            //保存到数据库
            substationService.insertSign(sign);
            //修改订单状态
            Task task = taskService.getTaskByTaskId(sign.getTaskId());
            Order order = orderService.getOrder(task.getOrderId());
            order.setStatus(6);
            orderService.updateOrder(order);
            return signId;
        }else{
            return "exist";
        }
    }

    //提交签收单：表单，涉及图片上传；上传后返回配送员主页；暂未实现，无需求
    /*
    @PostMapping("/sign")
    public String postSign(@RequestBody String signId){
        String msg = "";        //要返回的提示信息
        //检查签收单号是否正确
        Sign sign = substationService.getSignBySignId(signId);
        if(sign == null) msg = "not exist";     //签收单号不存在
        else {
            //图片处理！！


            //保存到数据库！！
            msg = "ok";
        }

        return msg;
    }
    */


    //回执录入：表单，上传后回配送员主页
    @PostMapping("/distributor/receipt")
    public String postReceipt(@RequestBody Receipt receipt){
        String msg = "";            //要返回的内容
        //判断是否是正确的taskId
        Task task = substationService.getTaskByTaskId(receipt.getTaskId());
        if(task==null) msg = "not exist";
        else {
            //判断是否已经提交过回执
            Receipt tempReceipt = substationService.getReceiptByTaskId(task.getTaskId());
            //已经提交过
            if(tempReceipt!=null) msg = "has receipt";
            else {
                //系统生成receiptId
                Date date = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
                String dateStr = formatter.format(date);
                System.out.println(dateStr);
                String receiptId = "RE" + dateStr;
                receipt.setReceiptId(receiptId);
                //distributionSituation和taskId已经自动获得
                //回执单存入数据库
                substationService.insertReceipt(receipt);
                msg = receiptId;

                //修改任务单状态：3 完成
                task.setStatus(3);
                substationService.updateTask(task);
                //修改订单状态：6 用户已签收
                Order order = orderService.getOrder(task.getOrderId());
                order.setStatus(6);
                orderService.updateOrder(order);
            }
        }
        return msg;
    }


    //配送员登录（管理员登录直接用的总站的）
    //新建配送员？？
    //@CrossOrigin(origins="http://localhost:8081",maxAge=3600)
    @PostMapping("/distributor")
    public Distributor login(@RequestBody Distributor distributor){
        Distributor distributor2 = substationService.getDistributor(distributor.getDistributorId());
        System.out.println(distributor.getDistributorId());
        System.out.println(distributor2);
        if(distributor2 == null) return null;    //由前端来处理是否登录成功
        else {
            System.out.println("disId:"+distributor2.getDistributorId());
            return distributor2;
        }
    }

    //依据管理员选择的时间段(年月份），得到orderId->查找对应的商品->统计
    //以键值对方式返回每种商品对应的收款，以及收款总额、退款总额
    @GetMapping("/moneyManage/{yearmonth}")
    public Map<String, BigDecimal> getMoneyManage(@PathVariable("yearmonth") String yearmonth,@RequestParam("substationId") String substationId){
        //String yearmonth = codateStr[0]+'-'+codateStr[1];        //取2020-07-12中的年和月
        System.out.println("年月："+yearmonth);

        //-----------------收款---------------

        //获得month月内的所有收款单
        List<Pay> payList = substationService.getPayListBySubstationIdAndMonth('%'+yearmonth+'%',substationId);
        //依据收款单的orderId查到所有商品的种类、数量和单价
        HashMap<String,BigDecimal> hashMap = new HashMap<>();           //种类和对应的总收款
        System.out.println("size: "+payList.size());
        for(int i=0;i<payList.size();i++){
            Pay pay = payList.get(i);
            List<LineItem> lineItemList = lineItemMapper.getLineItemsByOrderId(pay.getOrderId());
            for(int j=0;j<lineItemList.size();j++){
                BigDecimal tempPrice = hashMap.get(lineItemList.get(j).getItemId());
                //如果没有，就插入该记录
                if(tempPrice==null){
                    hashMap.put(lineItemList.get(j).getItemId(),lineItemList.get(j).getListprice().multiply(new BigDecimal(lineItemList.get(j).getNumber())));
                    System.out.println("当前总价："+hashMap.get(lineItemList.get(j).getItemId()));
                }else{      //如果有，就增加总价
                    hashMap.put(lineItemList.get(j).getItemId(),tempPrice.add(lineItemList.get(j).getListprice().multiply(new BigDecimal(lineItemList.get(j).getNumber()))));
                }
            }
        }

        //计算收款总额
        BigDecimal allPayMoney = new BigDecimal(0);
        for(int i=0;i<payList.size();i++){
            allPayMoney = allPayMoney.add(new BigDecimal(payList.get(i).getAmountOfmoney()));
        }

        //-----------------退款---------------

        //获得month月内的所有退款单
        List<Refund> refundList = substationService.getRefundListBySubstationIdAndMonth(yearmonth,substationId);
        BigDecimal allRefundMoney = new BigDecimal(0);
        //计算退款总额
        for(int i=0;i<refundList.size();i++){
            allRefundMoney = allRefundMoney.add(new BigDecimal(refundList.get(i).getAmountOfmoney()));
        }

        //整合
        hashMap.put("总收款",allPayMoney);
        hashMap.put("总退款",allRefundMoney);

        if(payList.size()==0) return null;
        else return hashMap;
    }

}

